# 作者: 家里蹲 吴越洋
# 2023年03月08日18时12分14秒
from socket import *
import struct

class Client:
    def __init__(self,ip,port):
        self.ip=ip
        self.port=port
        self.client_socket=None

    def connection(self):
        client_socket=socket(AF_INET,SOCK_STREAM)
        # 本地IP地址和端口
        address = (self.ip, self.port)
        client_socket.connect(address)
        self.client_socket=client_socket

    def send_train(self,new_socket:socket,data:str):
        data_bytes=data.encode('utf8')
        data_len=len(data_bytes)
        # 发火车头
        new_socket.send(struct.pack('I',data_len))
        # 发内容
        new_socket.send(data_bytes)

    def recv_train(self,new_socket:socket):
        # 接受火车头
        train_len=new_socket.recv(4)
        # 解包获得文件长度
        train_content_len=struct.unpack('I',train_len)[0]
        # 接受内容
        train_content=new_socket.recv(train_content_len)
        return train_content.decode('utf8')

    def user_operation(self):
        while True:
            #输入命令
            command=input()
            self.send_train(self.client_socket,command)
            data=self.recv_train(self.client_socket)
            print(data,end='')

if __name__ == '__main__':
    c=Client('192.168.0.109',3000)
    c.connection()
    c.user_operation()